package com.hongye.proprietary.mq;

import com.hongye.common.utils.MsgUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 监听短信的队列
 * @author lins
 * @date 2021/10/18 16:16
 */
@Slf4j
@Component
public class SmsConsumer {
    @Autowired
    private RedisTemplate redisTemplate;
    //参数可以为实体类  自己建一个需要的vo
    @RabbitListener(queues = "sms-queue")
    public void sendMsg(String phone, Channel channel, Message message) throws IOException {
        try {
            //TODO 发送短信
            String s = MsgUtil.sendMsg(phone);
            log.info("收到的验证码为："+s);
            //存redis
            redisTemplate.opsForValue().set(phone,s,90, TimeUnit.SECONDS);
            //执行业务逻辑成功,手动删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            //执行业务逻辑失败,将消息放回队列让别人执行
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
